import React, { Component } from 'react'
import request from '../../utils/request'

export default class TodoHeader extends Component {
  state = {
    name: '',
  }
  // 1. 收集数据
  // 2. 调用接口添加收集到的数据到后端
  // 3. 重新获取数据
  handleChange = (e) => {
    this.setState({ name: e.target.value })
  }
  handleKeyUp = async (e) => {
    if (e.keyCode === 13) {
      if (this.state.name.trim() === '') return
      // await request.post('/', { name: this.state.name, done: false })
      await request({
        method: 'POST',
        data: { name: this.state.name, done: false },
      })
      this.setState({ name: '' })
      this.props.getList()
    }
  }
  render() {
    const { name } = this.state
    return (
      <header className='header'>
        <h1>todos</h1>
        <input
          className='new-todo'
          placeholder='What needs to be done?'
          autoFocus
          value={name}
          onChange={this.handleChange}
          onKeyUp={this.handleKeyUp}
        />
      </header>
    )
  }
}
